// pages/login/login.js
const httprequest = require('../../utils/http_utils.js')
let utils = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    error: '', //错误提示信息
    success: '', //成功提示信息
    username: '', //用户名
    password: '', //密码
    showlogin: false, //是否显示输入用户名和密码
    scene: "",      //  测试 获取扫码进来的二维码携带的参数
  },

  giveAuthorize: function (e) {
    var that = this
    wx.login({
      success: function (res) {
        console.log('授权中:code--', res.code)
        // that.GetOpenId(res.code)
      }
    })
  },

  bindusernameinput: function (e) {
    this.setData({
      username: e.detail.value
    })
  },

  bindpasswordinput: function (e) {
    password: e.detail.value
  },

  // submitForm(e) {
  //   var that = this
  //   const params = e.detail.value
  //   if (params.username.length == 0) {
  //     this.setData({
  //       error: '请输入用户名'
  //     })
  //   } else if (params.password.length == 0) {
  //     this.setData({
  //       error: '请输入密码'
  //     })
  //   } else {
  //     console.log(wx.getStorageSync('openid')+"----------------------------------openId")
  //     var url = ''
  //     if (wx.getStorageSync('openid') != undefined && wx.getStorageSync('openid') != '') {
  //       var paramsInfo = {
  //         loginid: params.username,
  //         password: params.password,
  //         OpenId: wx.getStorageSync('openid') == "" || wx.getStorageSync('openid') == undefined ? '' : wx.getStorageSync('openid')
  //       }
  //       url = httprequest.apiInfo.GetLoginOpenidApi
  //     } else {
  //       var paramsInfo = {
  //         loginid: params.username,
  //         password: params.password
  //       }
  //       url = httprequest.apiInfo.UserLogin
  //     }
  //     httprequest.dologinRequest(url, paramsInfo,
  //       function(res) {
  //         console.log(JSON.stringify(res)+"---------用户信息")
  //         if (res.Data.Flag) {
  //           that.setData({
  //             success: '登录成功'
  //           })
  //           wx.setStorageSync("Ticket", res.Data.Ticket);
  //           wx.setStorageSync("UserInfo", res.Data);
  //           wx.setStorageSync("SessionId", res.SessionId);
  //           wx.setStorageSync('loginId', params.username)
  //           wx.setStorageSync('password', params.password)
  //           httprequest.getDicRequest(httprequest.apiInfo.GetAllDictionary, null,
  //             function(res) {
  //               wx.setStorageSync("Dictionary", res)
  //               wx.redirectTo({
  //                 url: '../index/index',
  //               })
  //             },
  //             function(err) {
  //               console.error(err)
  //               that.setData({
  //                 error: '登录失败'
  //               })
  //             })
  //         } else {
  //           that.setData({
  //             error: '用户名或密码错误'
  //           })
  //         }

  //       },
  //       function(err) {
  //         console.error(err)
  //         that.setData({
  //           error: '登录失败'
  //         })
  //       })
  //   }

  // },

  submitForm(e) {
    var that = this

    if (wx.getStorageSync('loginId') == "" && wx.getStorageSync('password') == "" || wx.getStorageSync('loginId') == null && wx.getStorageSync('password') == null) {
      var params = e.detail.value
    } else {
      var params = e
    }
    console.log(JSON.stringify(params)+'-------------缓存')
    console.log(typeof params)
    if (params.username.length == 0) {
      this.setData({
        error: '请输入用户名'
      })
    } else if (params.password.length == 0) {
      this.setData({
        error: '请输入密码'
      })
    } else {
      var url = ''
      var paramsInfo = {
        loginid: params.username,
        password: params.password
      }
      url = httprequest.apiInfo.UserLogin
      httprequest.dologinRequest(url, paramsInfo,
        function (res) {
          console.log(JSON.stringify(res) + "---------用户信息")
          if (res.Data.Flag) {
            that.setData({
              success: '登录成功'
            })
            wx.setStorageSync("Ticket", res.Data.Ticket);
            wx.setStorageSync("UserInfo", res.Data);
            wx.setStorageSync("SessionId", res.SessionId);
            wx.setStorageSync('loginId', params.username)
            wx.setStorageSync('password', params.password)
            console.log(wx.getStorageSync('loginId') + '---------------' + wx.getStorageSync('password'))
            httprequest.getDicRequest(httprequest.apiInfo.GetAllDictionary, null,
              function (res) {
                wx.setStorageSync("Dictionary", res)
                wx.redirectTo({
                  url: '../index/index',
                })
              },
              function (err) {
                console.error(err)
                that.setData({
                  error: '登录失败'
                })
              })
          } else {
            wx.clearStorageSync();
            that.setData({
              error: '用户名或密码错误',
              showlogin:true
            })
          }

        },
        function (err) {
          wx.clearStorageSync();
          console.error(err)
          that.setData({
            error: '登录失败'
          })
        })
    }

  },

  //清空文本框
  clear: function (e) {
    var name = e.currentTarget.dataset.name;
    if (name == 'username') {
      this.setData({
        username: ''
      })
    } else if (name == 'password') {
      this.setData({
        password: ''
      })
    }
  },

  //请求后台，code换取openid
  GetOpenId(code) {
    var that = this
    var param = {
      code: code
    }
    wx.request({
      url: httprequest.host + httprequest.apiInfo.GetOpenIdApi,
      data: param,
      method: 'GET',
      header: {
        'content-type': "application/x-www-form-urlencoded",
        'Authorization': "",
        'mobile': '0',
        'UserName': "",
        'Cache-Control': 'max-age=2000000, no-cache'
      },
      success: function (res) {
        if (res.data != null) {
          wx.setStorageSync('openid', res.data.openid)
          console.log(wx.getStorageSync('openid') + "-----------------获取OPENID")
          // that.OpenIdIsExist(wx.getStorageSync('openid'))
        } else {
          that.setData({
            info: '自动登录失败，请手动登录',
            showlogin: true
          })
        }
      },
      fail: function (err) {
        console.error(JSON.stringify(err) + "123")
      }
    })
  },

  //判断当前openid是否有关联关系
  OpenIdIsExist(openid) {
    var that = this
    var param2 = {
      OpenID: openid
    }
    wx.request({
      url: httprequest.host + httprequest.apiInfo.OpenIdIsExistApi,
      data: param2,
      method: 'GET',
      header: {
        'content-type': "application/x-www-form-urlencoded",
        'Authorization': "",
        'mobile': '0',
        'UserName': "",
        'Cache-Control': 'max-age=2000000, no-cache'
      },
      success: function (res) {
        if (res.data.code == '200') {
          console.log("有关联关系")
          wx.setStorageSync('loginId', res.data.loginId)
          wx.setStorageSync('password', res.data.password)
          // that.AutoLogin()
        } else {
          console.log("没有关联关系")
          that.setData({
            showlogin: true
          })
        }
      },
      fail: function (err) {
        console.error(err)
      }
    })
  },

  //自动登录
  AutoLogin() {
    var that = this
    console.log(wx.getStorageSync('password')+"------------密码")
    if (wx.getStorageSync('loginId') != undefined && wx.getStorageSync('loginId') != '' &&
      wx.getStorageSync('password') != undefined && wx.getStorageSync('password') != '') {
      wx.showLoading({
        title: "自动登录中...",
      })
      
      var paramsInfo = {
        loginid: wx.getStorageSync('loginId'),
        password: wx.getStorageSync('password'),
        OpenId: wx.getStorageSync('openid')
      }
      httprequest.dologinRequest(httprequest.apiInfo.GetLoginOpenidApi, paramsInfo,
        function (res) {
          console.log(JSON.stringify(res)+'---------------自动登录返回')
          wx.hideLoading();
          if (res.Data.Flag) {
            that.setData({
              success: '自动登录成功'
            })
            setTimeout(function () {
              wx.setStorageSync("Ticket", res.Data.AppLogin.Ticket);
              wx.setStorageSync("UserInfo", res.Data);
              wx.setStorageSync("SessionId", res.Data.AppLogin.SessionId);
              httprequest.getDicRequest(httprequest.apiInfo.GetAllDictionary, null,
                function (res) {
                  wx.setStorageSync("Dictionary", res)
                  wx.redirectTo({
                    url: '../index/index',
                  })
                },
                function (err) {
                  console.log("获取数据字典失败")
                  console.error(err)
                  that.setData({
                    error: '自动登录失败，请手动登录',
                    showlogin: true
                  })
                })
            }, 1500)
          } else {
            console.log("登录失败")
            that.setData({
              error: '自动登录失败，请手动登录',
              showlogin: true
            })
          }
        },
        function (err) {
          console.error(err)
          console.log("接口异常")
          that.setData({
            error: '自动登录失败，请手动登录',
            showlogin: true
          })
        })
    } else {
      that.setData({
        showlogin: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    wx.login({
      success: function (res) {
        console.log('onLoad:code--', res.code)
        // that.GetOpenId(res.code)
      }
    })

    if (wx.getStorageSync('loginId') == "" && wx.getStorageSync('password') == "" || wx.getStorageSync('loginId') == null && wx.getStorageSync('password') == null) {
      that.setData({
        showlogin: true
      })
    } else {
      that.setData({
        showlogin: false
      })
      var param = {
        username: wx.getStorageSync('loginId'),
        password: wx.getStorageSync('password')
      }
      that.submitForm(param);
    }


    // this.giveAuthorize()


    // options 中的scene需要使用decodeURIComponent才能获取到生成二维码时传入的scene
    // var scene = decodeURIComponent(options.q)//参数二维码传递过来的参数

    // console.log(scene +"scene")
    // console.log(utils.isEmptyObject(scene))
    // console.log(utils.isEmptyObject(undefined))
    console.log(options)

    // if (utils.isEmptyObject(scene) || scene == "undefined"){
    //   that.setData({
    //     scene: "",
    //   })
    // } else {
    //   that.setData({
    //     scene: scene,
    //   })
    // }



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})